// pages/bread/breadindex.js
var app = getApp();
var car = require('../../template/car/cakecar.js');
var category = require('../../template/category/cakecategory.js');
var cakebuy = require('../../template/cakebuy/cakebuy.js');
var allCake;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    topNeedShow: true,
    scrolltop: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    car.init(this);

    cakebuy.init(this, this.addCarCallBack, this.buyCallBack);

    if (app.globalData.address) {
      var address = app.globalData.address;
      this.setData({
        address: address
      });
    }

    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        var imghgt = res.windowWidth * 337 / 600;
        that.setData({
          imghgt: imghgt,
          scrollhgt: res.windowHeight
        });
      },
    });

    this.loadCakeList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.selectAddress.status == 1) {
      var address = app.globalData.selectAddress.value;
      this.setData({
        address: address
      });
      app.globalData.selectAddress.status = -1;
      app.globalData.selectAddress.value = null;

      this.loadCakeList();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  changeCakeType: function (e) {
    var btype = e.currentTarget.dataset.btype;
    this.setData({
      breadtype: btype
    });
  },
  loadCakeList: function () {
    app.appShowLoading(60000);
    var that = this;
    if (app.globalData.address == undefined || app.globalData.address == null) {
      app.getAddress();
      var timeid = setTimeout(function () {
        clearTimeout(timeid);
        that.loadCakeList();
      }, 1000);
      return;
    }
    if (this.data.address == null || this.data.address == undefined) {
      var address = app.globalData.address;
      this.setData({
        address: address
      });
    }

    var city = this.data.address.CITYID;
    var url = '/yuanmai_we/mcake/product/get/' + city;
    var property = {
      location: this.data.address.LOCATION,
      hasAddress: true,
      city: this.data.address.CITYNAME,
      county: this.data.address.COUNTYNAME,
      address: this.data.address.ADDRESS
    };
    url = url + '?datas=' + encodeURIComponent(JSON.stringify(property));
    app.loadDataFromServer(url, this.cakeListCallBack, {}, 'get');
  },
  cakeListCallBack: function (res) {
    console.log(res);
    wx.hideToast();
    if (res.data.products == null || res.data.products == undefined) {
      this.setData({
        breadlist: []
      });
      wx.showModal({
        title: '',
        content: '当前地区没有商品可销售，是否返回首页？',
        confirmColor: '#a08257',
        confirmText: '是',
        cancelText: '否',
        success: function (res) {
          if (res.confirm) {
            wx.switchTab({
              url: '../index/index',
            });
          }
        }
      });
      return;
    }
    // -------- 初始化-------分类
    var cgritems = res.data.flavorList;
    cgritems.unshift({ name: '全部', id: '0' });
    category.init(this, cgritems, this.categoryChooseCallBack);
    var products = res.data.products.list;
    var cakelist = [];
    for (var i = 0; i < products.length; i++) {
      var cakeinfo = {};
      cakeinfo.goodsid = products[i].id;
      cakeinfo.name = products[i].name
      if (products[i].french != null && products[i].french != undefined) {
        cakeinfo.fullname = cakeinfo.name + ' ' + products[i].french;
      }
      else {
        cakeinfo.fullname = cakeinfo.name;
      }
      if (products[i].fname != null && products[i].fname != undefined) {
        cakeinfo.specs = products[i].fname.split(',');
      }
      else {
        cakeinfo.specs = [];
      }
      if (products[i].fid != null && products[i].fid != undefined) {
        cakeinfo.fid = products[i].fid;
      }
      else {
        cakeinfo.fid = '';
      }
      cakeinfo.img = products[i].limg;
      cakeinfo.icon = products[i].img
      cakeinfo.price = products[i].price;
      cakeinfo.intro = products[i].chineseBrief;
      cakeinfo.storeid = res.data.products.stationId;
      cakeinfo.weight = products[i].spec;
      cakeinfo.list = products[i].list;
      cakelist.push(cakeinfo);
    }
    this.setData({
      mid: res.data.mid,
      fid: res.data.fid,
      stationId: res.data.stationId,
      cakelist: cakelist,
      scrolltop: 0
    });
    allCake = cakelist;
  },
  buyCake: function (e) {
    var goodsindex = e.currentTarget.dataset.goodsindex;
    cakebuy.show(goodsindex);
  },
  addressHandle: function () {
    wx.showModal({
      title: '',
      content: '切换地址可能导致购物车中部分商品无效，是否继续？',
      confirmColor: '#a08257',
      confirmText: '是',
      cancelText: '否',
      success: function (res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '../my/address/address?type=select',
          });
        }
      }
    });
  },
  //-----------------------------------
  showCar: car.showCar,
  submitOrder: car.submitOrder,
  closeCar: car.closeCar,
  handleCount: car.handleCount,

  showCategory: category.show,
  closeCategory: category.close,
  chooseCategory: category.choose,

  chooseSpec: cakebuy.chooseSpec,
  closeCakeBuy: cakebuy.close,
  addCarAction: cakebuy.addCar,
  buyAction: cakebuy.buy,
  //------------------- scroll ------------------
  goodsScroll: function (e) {
    var topNeedShow = true;
    if (e.detail.deltaY < 0 && e.detail.scrollTop > 46) {
      topNeedShow = false;
    }
    if (this.data.cgr_show == true) {
      topNeedShow = true;
    }
    // this.setData({
    //   topNeedShow: topNeedShow
    // });
  },
  //-------------------CALL BACK FUC------------------
  categoryChooseCallBack: function (category_code) {
    console.log(category_code);
    if (category_code.id.toString() == '0') {
      this.setData({
        cakelist: allCake
      });
    }
    else {
      var cakelist = [];
      for (var i = 0; i < allCake.length; i++) {
        var fidArr = allCake[i].fid.split(',');
        if (fidArr.indexOf(category_code.id.toString()) >= 0) {
          cakelist.push(allCake[i]);
        }
      }
      for (var i = 0; i < allCake.length; i++) {
        if (cakelist.indexOf(allCake[i]) < 0) {
          cakelist.push(allCake[i]);
        }
      }
      this.setData({
        scrolltop: 0,
        cakelist: cakelist
      });
    }
    category.close();
  },
  addCarCallBack: function () {
    var goodsinfo = this.data.cakelist[this.data.goodsindex];
    // console.log(goodsinfo);
    var small_img = goodsinfo.list[this.data.curspec].pic.url + goodsinfo.list[this.data.curspec].pic.list[0].s;
    var nameSpec = goodsinfo.name + ' ' + goodsinfo.list[this.data.curspec].spec;
    var data = {
      options: '1',
      goodsid: goodsinfo.list[this.data.curspec].id,
      price: goodsinfo.list[this.data.curspec].price,
      sku: goodsinfo.list[this.data.curspec].sku,
      spec: goodsinfo.list[this.data.curspec].spec,
      size: goodsinfo.list[this.data.curspec].size,
      tips: goodsinfo.list[this.data.curspec].edible,
      name: nameSpec,
      shortname: goodsinfo.name,
      img: goodsinfo.img,
      icon: goodsinfo.icon,
      image: small_img,
    };
    console.log(data);
    car.handleCount(data);
  },
  buyCallBack: function () {
    if (this.data.address == null || this.data.address == undefined) {
      wx.showToast({
        title: '请先添加收货地址！',
        icon: 'none'
      });
      return;
    }
    var goodsinfo = this.data.cakelist[this.data.goodsindex];
    var small_img = goodsinfo.list[this.data.curspec].pic.url + goodsinfo.list[this.data.curspec].pic.list[0].s;
    var nameSpec = goodsinfo.name + ' ' + goodsinfo.list[this.data.curspec].spec;
    var goods = {
      goodsid: goodsinfo.list[this.data.curspec].id,
      ID: goodsinfo.list[this.data.curspec].id,
      price: goodsinfo.list[this.data.curspec].price,
      sku: goodsinfo.list[this.data.curspec].sku,
      spec: goodsinfo.list[this.data.curspec].spec,
      size: goodsinfo.list[this.data.curspec].size,
      tips: goodsinfo.list[this.data.curspec].edible,
      name: nameSpec,
      shortname: goodsinfo.name,
      img: goodsinfo.img,
      icon: goodsinfo.icon,
      image: small_img,
      num: '1'
    };
    var orderinfo = {
      mid: this.data.mid,
      fid: this.data.fid,
      stationId: this.data.stationId,
      goodslist: [goods]
    }
    var urlstr = '../neworder/neworder?type=cake&orderinfo=' + encodeURIComponent(JSON.stringify(orderinfo)) + '&address=' + encodeURIComponent(JSON.stringify(this.data.address));
    wx.navigateTo({
      url: urlstr,
    });
  },
  //-----------------------------------------
  toPageTop: function () {
    this.setData({
      scrolltop: 0
    });
  },
  cakeDetail: function (e) {
    var indexval = e.currentTarget.dataset.goodsindex;
    var goods = encodeURIComponent(JSON.stringify(this.data.cakelist[indexval]));
    wx.navigateTo({
      url: './cakedetail/cakedetail?goods=' + goods,
    });
  }
})